import React, { useState } from 'react';
import authService from '../services/authService';
import './UserInfo.css';

const UserInfo = ({ user, onLogout, onOpenAdminPanel }) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const [isLoggingOut, setIsLoggingOut] = useState(false);

  const handleLogout = async () => {
    if (isLoggingOut) return;
    
    setIsLoggingOut(true);
    try {
      await authService.logout();
      onLogout();
    } catch (error) {
      console.error('登出失败:', error);
    } finally {
      setIsLoggingOut(false);
    }
  };

  const handleOpenAdminPanel = () => {
    setShowDropdown(false);
    if (onOpenAdminPanel) {
      onOpenAdminPanel();
    }
  };

  const toggleDropdown = () => {
    setShowDropdown(!showDropdown);
  };

  // 点击外部区域关闭下拉菜单
  React.useEffect(() => {
    const handleClickOutside = (event) => {
      if (!event.target.closest('.user-info')) {
        setShowDropdown(false);
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  if (!user) {
    return null;
  }

  // 获取用户名首字母作为头像
  const avatarLetter = user.username ? user.username.charAt(0).toUpperCase() : 'U';
  const isAdmin = user.role === 'admin';

  return (
    <div className="user-info">
      <div className="user-avatar" onClick={toggleDropdown}>
        <span className="avatar-letter">{avatarLetter}</span>
        {isAdmin && <span className="admin-badge">管</span>}
      </div>
      
      <div className="user-details" onClick={toggleDropdown}>
        <span className="user-name">
          {user.username}
          {isAdmin && <span className="admin-label">（管理员）</span>}
        </span>
        <span className="user-email">{user.email}</span>
      </div>
      
      <button 
        className="dropdown-toggle"
        onClick={toggleDropdown}
        aria-label="用户菜单"
      >
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path 
            d="M4 6L8 10L12 6" 
            stroke="currentColor" 
            strokeWidth="2" 
            strokeLinecap="round" 
            strokeLinejoin="round"
          />
        </svg>
      </button>
      
      {showDropdown && (
        <div className="user-dropdown">
          <div className="dropdown-header">
            <div className="dropdown-avatar">
              <span className="avatar-letter">{avatarLetter}</span>
              {isAdmin && <span className="admin-badge">管</span>}
            </div>
            <div className="dropdown-user-info">
              <div className="dropdown-username">
                {user.username}
                {isAdmin && <span className="admin-label">（管理员）</span>}
              </div>
              <div className="dropdown-email">{user.email}</div>
            </div>
          </div>
          
          <div className="dropdown-divider"></div>
          
          <div className="dropdown-menu">
            <div className="dropdown-item info-item">
              <div className="info-label">手机号码</div>
              <div className="info-value">{user.phone || '未设置'}</div>
            </div>
            
            <div className="dropdown-item info-item">
              <div className="info-label">医院</div>
              <div className="info-value">{user.hospital || '未设置'}</div>
            </div>
            
            <div className="dropdown-item info-item">
              <div className="info-label">职位</div>
              <div className="info-value">{user.position || '未设置'}</div>
            </div>
            
            <div className="dropdown-item info-item">
              <div className="info-label">用户角色</div>
              <div className="info-value">
                <span className={`role-badge ${isAdmin ? 'admin' : 'user'}`}>
                  {isAdmin ? '管理员' : '普通用户'}
                </span>
              </div>
            </div>
            
            <div className="dropdown-item info-item">
              <div className="info-label">注册时间</div>
              <div className="info-value">
                {new Date(user.created_at).toLocaleDateString('zh-CN')}
              </div>
            </div>
            
            <div className="dropdown-item info-item">
              <div className="info-label">账户状态</div>
              <div className="info-value">
                <span className={`status-badge ${user.is_active ? 'active' : 'inactive'}`}>
                  {user.is_active ? '正常' : '禁用'}
                </span>
              </div>
            </div>
          </div>
          
          <div className="dropdown-divider"></div>
          
          {/* 管理员功能区 */}
          {isAdmin && (
            <>
              <button 
                className="dropdown-item admin-panel-button"
                onClick={handleOpenAdminPanel}
              >
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path 
                    d="M8 1L10.5 6L16 6.75L12 10.5L13 16L8 13.25L3 16L4 10.5L0 6.75L5.5 6L8 1Z" 
                    stroke="currentColor" 
                    strokeWidth="1.5" 
                    strokeLinecap="round" 
                    strokeLinejoin="round"
                  />
                </svg>
                管理员面板
              </button>
              <div className="dropdown-divider"></div>
            </>
          )}
          
          <button 
            className={`dropdown-item logout-button ${isLoggingOut ? 'loading' : ''}`}
            onClick={handleLogout}
            disabled={isLoggingOut}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path 
                d="M6 2H2V14H6M11 11L14 8L11 5M14 8H6" 
                stroke="currentColor" 
                strokeWidth="1.5" 
                strokeLinecap="round" 
                strokeLinejoin="round"
              />
            </svg>
            {isLoggingOut ? '登出中...' : '登出'}
          </button>
        </div>
      )}
    </div>
  );
};

export default UserInfo; 